
using AutoMapper;
using DTO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Model;
using SqlSugar;
using Util;

namespace API.Controllers
{
    public class Base_UserController : BaseController
    {
        Repository<tBase_User> _Base_User;
        Repository<tBase_Department> _Department;
        Repository<tBase_UserRole> _UserRole;
        Repository<tBase_Role> _Role;
        readonly IMapper _mapper;
        public Base_UserController(Repository<tBase_User> Base_User, IMapper mapper, Repository<tBase_Department> department, Repository<tBase_UserRole> userRole, Repository<tBase_Role> role)
        {
            _Base_User = Base_User;
            _mapper = mapper;
            _Department = department;
            _UserRole = userRole;
            _Role = role;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> Save([FromBody] SaveBase_UserInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = _mapper.Map<tBase_User>(dto);
                InitEntity(model);
                await _Base_User.InsertOrUpdateAsync(model);

                //保存用户角色
                await _UserRole.DeleteAsync(x => x.FUserId == dto.Id);
                //if (dto.RoleIds.Count>0)
                //{
                //    tBase_UserRole userRoleModel = new tBase_UserRole();
                //    foreach (var item in dto.RoleIds)
                //    {
                //        userRoleModel = new tBase_UserRole();
                //        userRoleModel.FRoleId = item;
                //        userRoleModel.FUserId = dto.Id;
                //        userRoleModel.FDeleted = false;
                //        InitEntity(userRoleModel);
                //        await _UserRole.InsertAsync(userRoleModel);
                //    }
                //}
                tBase_UserRole userRoleModel = new tBase_UserRole();
                userRoleModel.FRoleId = dto.RoleId;
                userRoleModel.FUserId = dto.Id;
                userRoleModel.FDeleted = false;
                InitEntity(userRoleModel);
                await _UserRole.InsertAsync(userRoleModel);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_UserController--Save:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<Base_UserOutput>>> GetList([FromBody] Base_UserListInput dto)
        {
            ResultMsg<List<Base_UserOutput>> result = new ResultMsg<List<Base_UserOutput>>();
            try
            {
                if (dto.PageNum <= 0)
                {
                    return result.Error("PageNum不能小于或等于0");
                }
                if (dto.PageSize <= 0)
                {
                    return result.Error("PageSize不能小于或等于0");
                }
                SqlSugar.PageModel pageModel = new SqlSugar.PageModel
                {
                    PageIndex = dto.PageNum,
                    PageSize = dto.PageSize,
                };
                var exp = Expressionable.Create<tBase_User>();
                if (!string.IsNullOrWhiteSpace(dto.UserName))
                {
                    exp.And(x => x.FUserName.Contains(dto.UserName));
                }
                if (!string.IsNullOrWhiteSpace(dto.RealName))
                {
                    exp.And(x => x.FRealName.Contains(dto.RealName));
                }
                if (dto.Deleted != null)
                {
                    exp.And(x => x.FDeleted == dto.Deleted);
                }
                if (!string.IsNullOrEmpty(dto.DepartmentId))
                {
                    exp.And(x => x.FDeleted.Equals(dto.DepartmentId));
                }
                var list = _Base_User.GetPageList(exp.ToExpression(), pageModel).OrderByDescending(x => x.CreateTime).ToList();
                var Base_UserOutputs = _mapper.Map<List<Base_UserOutput>>(list);
                var depList = await _Department.GetListAsync(x => !x.FDeleted);

                var userRoleList = await _UserRole.GetListAsync(x => !x.FDeleted);
                foreach (var item in Base_UserOutputs)
                {
                    item.BirthdayStr = item.Birthday == null ? string.Empty : item.Birthday.ToString("yyyy-MM-dd");
                    item.DepartmentName = depList == null || depList.Count == 0 ? string.Empty : depList.Where(c => c.Id == item.DepartmentId).FirstOrDefault()?.FName;
                    item.SexStr = item.Sex == 0 ? "女" : "男";
                    item.RoleId=userRoleList.Where(c => c.FUserId == item.Id).FirstOrDefault()?.FRoleId;
                    if (!string.IsNullOrEmpty(item.RoleId))
                    {
                        item.RoleName = _Role.GetById(item.RoleId).FRoleName;
                    }
                }
                return result.Success(Base_UserOutputs, pageModel.TotalCount);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_UserController--GetList:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 获取唯一
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<Base_UserOutput>> GetTheOne(string id)
        {
            ResultMsg<Base_UserOutput> result = new ResultMsg<Base_UserOutput>();
            try
            {
                var model = await _Base_User.GetByIdAsync(id);
                var dao = _mapper.Map<Base_UserOutput>(model);

                var userRoleList = await _UserRole.GetListAsync(x => !x.FDeleted);
                dao.RoleId = userRoleList.Where(c => c.FUserId == id).FirstOrDefault()?.FRoleId;
                if (!string.IsNullOrEmpty(dao.RoleId))
                {
                    dao.RoleName = _Role.GetById(dao.RoleId).FRoleName;
                }
                //dao.RoleIds = (await _UserRole.GetListAsync(x => x.FUserId == dao.Id)).Select(x => x.FRoleId).ToList();
                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_UserController--GetTheOne:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<string>> Del(string id)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                await _Base_User.DeleteByIdAsync(id);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_UserController--Del:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 同步CRM数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResultMsg<string>> SyncCrmUser([FromBody] SyncCrmUserInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                if (string.IsNullOrEmpty(dto.UserId))
                {
                    return result.Error("UserId不能为空");
                }
                if (await _Base_User.IsAnyAsync(x => x.FUserId == dto.UserId))
                {
                    return result.Error("该用户已存在");
                }
                tBase_User model = new tBase_User();
                model.FUserId = dto.UserId;
                model.FUserName = dto.UserName;
                model.FRealName = dto.RealName;
                model.FSex = dto.Sex;
                model.FBirthday = dto.Birthday;
                model.FDeleted = false;
                model.FPassword = "";
                model.FPhoto = "";
                InitEntity(model);
                await _Base_User.InsertAsync(model);

                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("Base_UserController--SyncCrmUser:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
    }
}
